#include "cpu.h"
#include <QDebug>
#include <QRegularExpression>

CPU::CPU(InterruptManager* interruptManager)
    : interruptManager(interruptManager), pc(0), flags(0), halted(false)
{
    // 初始化寄存器
    registers["AX"] = 0;
    registers["BX"] = 0;
    registers["CX"] = 0;
    registers["DX"] = 0;
    registers["SI"] = 0;
    registers["DI"] = 0;
    registers["BP"] = 0;
    registers["SP"] = 1023; // 栈顶初始化为内存最高地址
    registers["IP"] = 0;
    
    // 初始化内存
    memory.resize(1024);
}

CPU::~CPU()
{
}

// 新增指令实现
void CPU::executePUSH(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: PUSH指令需要一个操作数";
        return;
    }
    
    QString operand = operands[0];
    int value;
    bool isReg;
    
    if (parseOperand(operand, value, isReg)) {
        // 减少栈指针
        registers["SP"] -= 1;
        
        // 将值压入栈
        if (registers["SP"] >= 0 && registers["SP"] < memory.size()) {
            memory[registers["SP"]] = value;
        } else {
            qDebug() << "错误: 栈溢出";
        }
    }
}

void CPU::executePOP(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: POP指令需要一个操作数";
        return;
    }
    
    QString dest = operands[0];
    
    if (isRegister(dest)) {
        if (registers["SP"] < memory.size()) {
            // 从栈中弹出值
            registers[dest] = memory[registers["SP"]];
            
            // 增加栈指针
            registers["SP"] += 1;
        } else {
            qDebug() << "错误: 栈下溢";
        }
    } else {
        qDebug() << "错误: POP指令的目标操作数必须是寄存器";
    }
}

void CPU::executeCALL(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: CALL指令需要一个操作数";
        return;
    }
    
    QString target = operands[0];
    bool ok;
    int address = target.toInt(&ok);
    
    if (ok) {
        // 保存返回地址
        executePUSH(QStringList() << QString::number(registers["IP"] + 1));
        
        // 设置新的指令指针
        registers["IP"] = address;
    } else {
        qDebug() << "错误: CALL指令的操作数必须是有效地址";
    }
}

void CPU::executeRET(const QStringList& operands)
{
    if (!operands.isEmpty()) {
        qDebug() << "错误: RET指令不接受操作数";
        return;
    }
    
    // 从栈中恢复返回地址
    executePOP(QStringList() << "IP");
}

void CPU::executeINC(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: INC指令需要一个操作数";
        return;
    }
    
    QString operand = operands[0];
    
    if (isRegister(operand)) {
        registers[operand] += 1;
        setFlags(registers[operand]);
    } else {
        qDebug() << "错误: INC指令的操作数必须是寄存器";
    }
}

void CPU::executeDEC(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: DEC指令需要一个操作数";
        return;
    }
    
    QString operand = operands[0];
    
    if (isRegister(operand)) {
        registers[operand] -= 1;
        setFlags(registers[operand]);
    } else {
        qDebug() << "错误: DEC指令的操作数必须是寄存器";
    }
}

void CPU::executeAND(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: AND指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString src = operands[1];
    
    if (isRegister(dest) && isRegister(src)) {
        registers[dest] = registers[dest] & registers[src];
        setFlags(registers[dest]);
    } else {
        qDebug() << "错误: AND指令只支持寄存器操作";
    }
}

void CPU::executeOR(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: OR指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString src = operands[1];
    
    if (isRegister(dest) && isRegister(src)) {
        registers[dest] = registers[dest] | registers[src];
        setFlags(registers[dest]);
    } else {
        qDebug() << "错误: OR指令只支持寄存器操作";
    }
}

void CPU::executeXOR(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: XOR指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString src = operands[1];
    
    if (isRegister(dest) && isRegister(src)) {
        registers[dest] = registers[dest] ^ registers[src];
        setFlags(registers[dest]);
    } else {
        qDebug() << "错误: XOR指令只支持寄存器操作";
    }
}

void CPU::executeNOT(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: NOT指令需要一个操作数";
        return;
    }
    
    QString operand = operands[0];
    
    if (isRegister(operand)) {
        registers[operand] = ~registers[operand];
        setFlags(registers[operand]);
    } else {
        qDebug() << "错误: NOT指令的操作数必须是寄存器";
    }
}

void CPU::executeSHL(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: SHL指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString count = operands[1];
    
    if (isRegister(dest)) {
        bool ok;
        int shiftCount = count.toInt(&ok);
        
        if (ok) {
            registers[dest] = registers[dest] << shiftCount;
            setFlags(registers[dest]);
        } else {
            qDebug() << "错误: SHL指令的第二个操作数必须是整数";
        }
    } else {
        qDebug() << "错误: SHL指令的第一个操作数必须是寄存器";
    }
}

void CPU::executeSHR(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: SHR指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString count = operands[1];
    
    if (isRegister(dest)) {
        bool ok;
        int shiftCount = count.toInt(&ok);
        
        if (ok) {
            registers[dest] = registers[dest] >> shiftCount;
            setFlags(registers[dest]);
        } else {
            qDebug() << "错误: SHR指令的第二个操作数必须是整数";
        }
    } else {
        qDebug() << "错误: SHR指令的第一个操作数必须是寄存器";
    }
}    

// 基本方法实现
int CPU::getRegister(const QString& regName) const
{
    return registers.value(regName, 0);
}

void CPU::setRegister(const QString& regName, int value)
{
    registers[regName] = value;
}

int CPU::getMemory(int address) const
{
    if (address >= 0 && address < memory.size()) {
        return memory[address];
    }
    return 0;
}

void CPU::setMemory(int address, int value)
{
    if (address >= 0 && address < memory.size()) {
        memory[address] = value;
    }
}

void CPU::executeInstruction(const QString& instruction)
{
    if (instruction.trimmed().isEmpty() || instruction.trimmed().startsWith(";")) {
        return; // 跳过空行和注释
    }
    
    QString trimmedInstruction = instruction.trimmed();
    QStringList parts = trimmedInstruction.split(QRegularExpression("\\s+"));
    
    if (parts.isEmpty()) {
        return;
    }
    
    QString opcode = parts[0].toUpper();
    QStringList operands;
    
    // 解析操作数
    if (parts.size() > 1) {
        QString operandStr = trimmedInstruction.mid(opcode.length()).trimmed();
        operands = operandStr.split(",");
        for (QString& operand : operands) {
            operand = operand.trimmed();
        }
    }
    
    // 执行指令
    if (opcode == "MOV") {
        executeMOV(operands);
    } else if (opcode == "ADD") {
        executeADD(operands);
    } else if (opcode == "SUB") {
        executeSUB(operands);
    } else if (opcode == "MUL") {
        executeMUL(operands);
    } else if (opcode == "DIV") {
        executeDIV(operands);
    } else if (opcode == "CMP") {
        executeCMP(operands);
    } else if (opcode == "JMP") {
        executeJMP(operands);
    } else if (opcode == "JE") {
        executeJE(operands);
    } else if (opcode == "JNE") {
        executeJNE(operands);
    } else if (opcode == "JG") {
        executeJG(operands);
    } else if (opcode == "JL") {
        executeJL(operands);
    } else if (opcode == "INT") {
        executeINT(operands);
    } else if (opcode == "PUSH") {
        executePUSH(operands);
    } else if (opcode == "POP") {
        executePOP(operands);
    } else if (opcode == "CALL") {
        executeCALL(operands);
    } else if (opcode == "RET") {
        executeRET(operands);
    } else if (opcode == "INC") {
        executeINC(operands);
    } else if (opcode == "DEC") {
        executeDEC(operands);
    } else if (opcode == "AND") {
        executeAND(operands);
    } else if (opcode == "OR") {
        executeOR(operands);
    } else if (opcode == "XOR") {
        executeXOR(operands);
    } else if (opcode == "NOT") {
        executeNOT(operands);
    } else if (opcode == "SHL") {
        executeSHL(operands);
    } else if (opcode == "SHR") {
        executeSHR(operands);
    } else if (opcode == "HLT") {
        halted = true;
    } else {
        qDebug() << "错误: 未知指令" << opcode;
    }
}

void CPU::reset()
{
    // 重置寄存器
    registers["AX"] = 0;
    registers["BX"] = 0;
    registers["CX"] = 0;
    registers["DX"] = 0;
    registers["SI"] = 0;
    registers["DI"] = 0;
    registers["BP"] = 0;
    registers["SP"] = 1023;
    registers["IP"] = 0;
    
    // 清空内存
    memory.fill(0);
    
    // 重置状态
    pc = 0;
    flags = 0;
    halted = false;
}

void CPU::triggerInterrupt(int interruptNumber)
{
    if (interruptManager) {
        interruptManager->triggerInterrupt(interruptNumber);
    }
}

bool CPU::isHalted() const
{
    return halted;
}

// 基本指令实现
void CPU::executeMOV(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: MOV指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString src = operands[1];
    
    int value;
    bool isReg;
    
    if (parseOperand(src, value, isReg)) {
        if (isRegister(dest)) {
            registers[dest] = value;
        } else if (dest.startsWith("[") && dest.endsWith("]")) {
            // 内存地址
            QString addrStr = dest.mid(1, dest.length() - 2);
            bool ok;
            int address = addrStr.toInt(&ok);
            if (ok) {
                setMemory(address, value);
            }
        }
    }
}

void CPU::executeADD(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: ADD指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString src = operands[1];
    
    if (isRegister(dest)) {
        int value;
        bool isReg;
        if (parseOperand(src, value, isReg)) {
            int result = registers[dest] + value;
            registers[dest] = result;
            setFlags(result);
        }
    }
}

void CPU::executeSUB(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: SUB指令需要两个操作数";
        return;
    }
    
    QString dest = operands[0];
    QString src = operands[1];
    
    if (isRegister(dest)) {
        int value;
        bool isReg;
        if (parseOperand(src, value, isReg)) {
            int result = registers[dest] - value;
            registers[dest] = result;
            setFlags(result, true);
        }
    }
}

void CPU::executeMUL(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: MUL指令需要一个操作数";
        return;
    }
    
    QString src = operands[0];
    int value;
    bool isReg;
    
    if (parseOperand(src, value, isReg)) {
        int result = registers["AX"] * value;
        registers["AX"] = result & 0xFFFF; // 低16位
        registers["DX"] = (result >> 16) & 0xFFFF; // 高16位
        setFlags(registers["AX"]);
    }
}

void CPU::executeDIV(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: DIV指令需要一个操作数";
        return;
    }
    
    QString src = operands[0];
    int value;
    bool isReg;
    
    if (parseOperand(src, value, isReg)) {
        if (value != 0) {
            int dividend = registers["AX"];
            registers["AX"] = dividend / value; // 商
            registers["DX"] = dividend % value; // 余数
            setFlags(registers["AX"]);
        } else {
            qDebug() << "错误: 除零错误";
        }
    }
}

void CPU::executeCMP(const QStringList& operands)
{
    if (operands.size() != 2) {
        qDebug() << "错误: CMP指令需要两个操作数";
        return;
    }
    
    QString src1 = operands[0];
    QString src2 = operands[1];
    
    int value1, value2;
    bool isReg1, isReg2;
    
    if (parseOperand(src1, value1, isReg1) && parseOperand(src2, value2, isReg2)) {
        int result = value1 - value2;
        setFlags(result, true);
    }
}

void CPU::executeJMP(const QStringList& operands)
{
    // 简化实现，仅用于演示
    qDebug() << "JMP指令执行";
}

void CPU::executeJE(const QStringList& operands)
{
    // 简化实现，仅用于演示
    qDebug() << "JE指令执行";
}

void CPU::executeJNE(const QStringList& operands)
{
    // 简化实现，仅用于演示
    qDebug() << "JNE指令执行";
}

void CPU::executeJG(const QStringList& operands)
{
    // 简化实现，仅用于演示
    qDebug() << "JG指令执行";
}

void CPU::executeJL(const QStringList& operands)
{
    // 简化实现，仅用于演示
    qDebug() << "JL指令执行";
}

void CPU::executeINT(const QStringList& operands)
{
    if (operands.size() != 1) {
        qDebug() << "错误: INT指令需要一个操作数";
        return;
    }
    
    bool ok;
    int interruptNumber = operands[0].toInt(&ok);
    if (ok) {
        triggerInterrupt(interruptNumber);
    }
}

// 辅助函数实现
bool CPU::parseOperand(const QString& operand, int& value, bool& isRegister)
{
    isRegister = false;
    
    if (this->isRegister(operand)) {
        isRegister = true;
        value = registers[operand];
        return true;
    } else if (operand.startsWith("$")) {
        // 立即数
        bool ok;
        value = operand.mid(1).toInt(&ok);
        return ok;
    } else if (operand.startsWith("[") && operand.endsWith("]")) {
        // 内存地址
        QString addrStr = operand.mid(1, operand.length() - 2);
        bool ok;
        int address = addrStr.toInt(&ok);
        if (ok) {
            value = getMemory(address);
            return true;
        }
    } else {
        // 尝试作为数字解析
        bool ok;
        value = operand.toInt(&ok);
        return ok;
    }
    
    return false;
}

void CPU::setFlags(int result, bool isSubtract)
{
    // 零标志
    if (result == 0) {
        flags |= 0x40; // ZF
    } else {
        flags &= ~0x40;
    }
    
    // 符号标志
    if (result < 0) {
        flags |= 0x80; // SF
    } else {
        flags &= ~0x80;
    }
    
    // 更新FLAGS寄存器
    registers["FLAGS"] = flags;
}

bool CPU::isRegister(const QString& regName) const
{
    return registers.contains(regName);
}    
